<template>
  <div class="wrap-container sn-container">
    <div class="sn-content">
      <div class="sn-title">班级学生成绩</div>
      <div class="select">
        <el-select v-model="selectItem" placeholder="请选择任务">
          <el-option v-for="item in periodList" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="sn-body">
        <div class="wrap-container">
          <div class="pd-main">
            <div id="classScore" class="chart-1"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
// import { getText } from "./../common.js";

export default {
  name: "allStudentScore",
  props: {
    allData: {
      type: Array,
      default() {
        return [];
      },
    },
    dictData: {
      type: Array,
      default() {
        return [];
      },
    },
    studentList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      timer: null,
      number: null,
      arr: [],
      periodList: [],
      selectItem: "",
      num: 0,
      chartData: [],
      xAxiosNames: [],
    };
  },
  watch: {
    allData: {
      handler() {
        this.getData();
      },
      deep: false, 
    },
    selectItem: {
      handler(val) {
        if (val) { 
          this.getEchart();
        }
      },
      deep: false,
    },
  },
  mounted() {
     // this.getData();
  },
  methods: {
    getData() {
      const list = this.allData.filter((el) => el.scoreType === "1");
      this.chartData = list;
      if (list.length > 0) {
        this.xAxiosNames = list.map((el) => el.period);
        const temp = [];
        list
          .map((el) => el.period)
          .forEach((el) => {
            if (!temp.includes(el)) {
              temp.push(el);
            }
          });
        this.periodList = temp.sort((a, b)=> a.localeCompare(b, 'zh')); //a~z 排序  
        this.selectItem = this.periodList[0]; 
      }

      // this.initData();
    },
    initData() {
      this.num = 0;
      // this.timer = setInterval(() => {
      //   this.switchItem();
      // }, 4000);
      this.switchItem();
    },
    switchItem() {
      this.num += 1;
      if (this.num > this.periodList.length - 1) {
        this.num = 0;
      } 
      const period = this.periodList[this.num]
      this.selectItem = period; 
    },
    getEchart() {
      const tempData = this.chartData.filter(
        (el) => this.selectItem === el.period
      );
      let dataScore = tempData.map((el) => {
        const sObj = {
          score0: 0,
          score1: 0,
          score2: 0,
          score: 0,
        };
        const tempScore = el.score.split(";");
        tempScore.forEach((s, i) => {
          s.split(",").forEach((k) => {
            sObj[`score${i}`] += Number(k);
          });
        });
        const { score0, score1, score2 } = sObj;
        sObj.score = ((score0 + score1 + score2) / 1.5).toFixed(1);
        sObj.name = el.stuName;
        return sObj;
      });
      // const taskName = []
      // tempData.forEach(el => {
      //   if(!taskName.includes(el.period)) {
      //     taskName.push(el.period)
      //   }
      // })
      const names = [];
      dataScore.forEach((el) => {
        if (!names.includes(el.name)) {
          names.push(el.name);
        }
      }); 

      const ds = new Array(this.studentList.length - dataScore.length).fill('')
      const mp = ds.map((el, i) => ({ name: `未录${i}`, score: null }))
      const finalData = [...dataScore, ...mp]
      const data = dataScore.length < this.studentList.length ? finalData : dataScore

      const series = [];
      // })
      const obj = {
        name: "",
        type: "bar",
        stack: "Total",
        label: {
          show: true,
          position: 'top',
          textStyle: {
            fontSize: 18,
            color: '#fff',
          }
        },
        // data:  dataScore.map((m) => m.score),
        data: data.map((m) => m.score),
        itemStyle: {
          // color: function (params) {
          //   var colorarrays = [
          //     "#5119e4",
          //     "#fd6975",
          //     "#dbdaad",
          //     "#7f99ea",
          //     "#3c05fa",
          //     "#9c65f4",
          //     "#32a78e",
          //     "#3ad94d",
          //     "#748259",
          //     "#b629e0",
          //     "#abde87",
          //     "#6edaf4",
          //   ];
          //   return colorarrays[params.dataIndex];
          // }, 
          color: function(){
             return {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#00CEFF' // 0% 处的颜色
              }, {
                offset: 1, color: '#6872FF' // 100% 处的颜色
              }],
              global: false // 缺省为 false
            }
          },
          barBorderRadius: [50, 50, 0, 0],//柱形图圆角设置
        }
      };
      series.push(obj);
      let myChart = echarts.init(document.getElementById("classScore")); // 图标初始化
      // if (!this.chartData.length) {
      //   myChart.dispose();
      //   return;
      // }
      const option = {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: names.length < this.studentList.length ? [...names, ...new Array(this.studentList.length - names.length).fill('')] : names,
          textStyle: {
            //图例文字的样式
            color: "#fff",
            fontSize: 16,
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category", 
          boundaryGap: true,//设置为true
          data: names.length < this.studentList.length ? [...names, ...new Array(this.studentList.length - names.length).fill('')] : names,
          axisLabel: {
            formatter: "{value}",
            color: "#fff",
            interval: 0,
            rotate: 45,
            //倾斜度 -90 至 90 默认为0  
            margin: 2,
            textStyle: {
              fontWeight: "bolder",
              fontSize: 16
            }
          },
        },
        yAxis: {
          type: "value",
          name: "单位（分）",
          nameTextStyle:{//y轴上方单位的颜色
              color:'#fff',
              fontSize: 16
            },
          axisLabel: {
            formatter: "{value}",
            color: "#fff",
          },
          min: 0,
          max: 100,
        },
        series,
      };
      myChart.setOption(option, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
};
</script>

<style lang="scss" scoped>
.sn-container {
  width: 1846px;
  left: 23px;
  top: 625px;
  height: 440px;

  .pd-main {
    position: absolute;
    height: 90%;
    width: 100%;

    [class^="chart"] {
      position: absolute;
      -webkit-transform-origin: left top;
      -moz-transform-origin: left top;
      -ms-transform-origin: left top;
      -o-transform-origin: left top;
      transform-origin: left top;
    }

    .chart-1 {
      width: 100%;
      height: 450px;
      top: 55%;
      left: 50%;
      -webkit-transform: translate(-50%, -50%);
      -moz-transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
      -o-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }
  }
}

.select {
  position: absolute;
  right: 0;
}
</style>
